package com.panfeng.xcloud.gateway.config;

import com.panfeng.xcloud.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.*;

/**
 * 分布式swagger文档提供者
 *
 * @author xiaobo
 * @date 2018-03-15
 */
@Component
@Primary
@Slf4j
public class DocumentationConfig implements SwaggerResourcesProvider {

	@Value("${xdcloud.swagger2.showdoc.applicationnames}")
	private String showdocs;

	private final RouteLocator routeLocator;

    public DocumentationConfig(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

	@Override
	public List<SwaggerResource> get() {
		List<SwaggerResource> resources = new ArrayList<SwaggerResource>();
		List<Route> routes = routeLocator.getRoutes();
		Map<String,String> appDocInfoMaps = new HashMap<>();
		if(StringUtils.isNotEmpty(showdocs)&& showdocs.indexOf(",") != -1){
			String[] appDocInfos = showdocs.split(",");
			if(null != appDocInfos && appDocInfos.length > 0){
				for (int i = 0 ; i < appDocInfos.length; i++){
					String appDocInfo = appDocInfos[i];
					if (StringUtils.isNotEmpty(appDocInfo)&& appDocInfo.indexOf(":") != -1){
						String[] appDoc = appDocInfo.split("\\:");
						if(null != appDoc && appDoc.length == 2){
							log.info(">>> 加载各个微服务分布式在线文档信息-服务名={}，文档标题={} <<<",appDoc[0],appDoc[1]);
							appDocInfoMaps.put(appDoc[0],appDoc[1]);
						}
					}
				}
			}
		}

		for (Route route : routes) {
			String routeId = route.getId();
			for (Iterator<String> it = appDocInfoMaps.keySet().iterator();it.hasNext();){
				String appName = it.next();
				if (routeId.indexOf(appName) != -1){
					resources.add(swaggerResource(appDocInfoMaps.get(appName), route.getFullPath().replace("**", "v2/api-docs"), "2.0"));
					break;
				}
			}
		}
		resources.add(swaggerResource("QuantBot gateway APIs", "/v2/api-docs?group=gateway", "2.0"));
		return resources;
	}

	private SwaggerResource swaggerResource(String name, String location,
			String version) {
		SwaggerResource swaggerResource = new SwaggerResource();
		swaggerResource.setName(name);
		swaggerResource.setLocation(location);
		swaggerResource.setSwaggerVersion(version);
		return swaggerResource;
	}
}
